package thread.safe;

import java.time.LocalDateTime;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author bc
 * @Description:
 * @date 2024/03/11
 */
@SuppressWarnings("ALL")
public class CyclicBarrierTest {

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        executorService.submit(() -> {
            System.out.println(LocalDateTime.now() + " 1号线程启动");

            try {
                Thread.sleep(5000);
                cyclicBarrier.await();
                System.out.println(LocalDateTime.now() + " 1号线程结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });

        executorService.submit(() -> {
            System.out.println(LocalDateTime.now() + " 2号线程启动");

            try {
                Thread.sleep(3000);
                cyclicBarrier.await();
                System.out.println(LocalDateTime.now() + " 2号线程结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });

        Thread.sleep(7000);
        cyclicBarrier.await();
    }
}
